﻿using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using ChapterX.Common;
using ChapterX.BusinessFacade;
using ChapterX.Data;
using ChapterX.Data.BooksDSTableAdapters;
using ChapterX.Data.ChaptersDSTableAdapters;

namespace ChapterX.Auth.Teacher
{
    public partial class SetAccessibility : ChapterX.Model.PageBase
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                int bookId;
                int courseId;

                if (Utils.HasValue(Request.QueryString[QueryKeys.BOOK_ID]) &&
                        Int32.TryParse(Utils.GetValue(Request.QueryString[QueryKeys.BOOK_ID]), out bookId))
                {
                    //book 必须绑定课程，否则无法设置访问权限
                    if (BindCourseList(bookId))
                    {
                        courseId = Int32.Parse(this.ddl_CourseList.SelectedValue);
                        BindChapterList(bookId, courseId);

                        this.hf_BookId.Value = bookId.ToString();

                        //如果设置过用户名和密码，需要绑定用户名和密码的值
                        BindAccount(bookId, courseId);
                    }
                }
            }
        }

        protected bool BindCourseList(int bookId)
        {
            CourseBookViewTableAdapter adpater = new CourseBookViewTableAdapter();
            DataTable table;
            if (CurrentUserInfo.IsLibrarian)
            {
                table = adpater.GetCourseListByBookId(bookId);
            }
            else
            {
                table = adpater.GetCourseListByBookIdAndTeacherId(bookId, CurrentUserInfo.Username);
            }

            if (table != null && table.Rows.Count > 0)
            {
                this.ddl_CourseList.DataSource = table;
                this.ddl_CourseList.DataTextField = "CourseName";
                this.ddl_CourseList.DataValueField = "CourseId";
                this.ddl_CourseList.DataBind();

                return true;
            }
            else
            {
                SetErrorMessage("课程绑定失败");
                return false;
            }
        }

        protected void BindChapterList(int bookId, int courseId)
        {
            //Get ChapterAccessView By BookId And CourseId
            ChaptersTableAdapter adapter = new ChaptersTableAdapter();
            DataTable chapterList = adapter.GetChaptersByBookId(bookId);

            this.rp_ChapterList.DataSource = chapterList;
            this.rp_ChapterList.DataBind();
        }

        protected void BindAccount(int bookId, int courseId)
        {
            AccessSystem accessSys = new AccessSystem();
            BooksDS.BookAccessRow row = accessSys.GetBookAccessByBookIdAndCourseId(bookId, courseId);

            if (row != null)
            {
                this.tb_UserName.Text = row.AccessAccount;
                this.tb_Pwd.Text = row.AccessCode;

                this.hf_Account.Value = row.AccessAccount;
            }
        }

        protected void Submit_Click(object sender, EventArgs e)
        {
            AccessSystem accs = new AccessSystem();

            int bookId;
            int courseId;

            try
            {
                if (this.tb_UserName.Text.Trim().Length == 0)
                {
                    throw new InvalidInputException("用户名不能为空");
                }
                else
                {
                    //TODO：从user表和book accessibility中检测用户名是否已经存在
                    //TOD：如果是新建，判断是否存在；不是新建，则修改用户名时判断是否存在
                    String inputAccount = this.tb_UserName.Text.Trim();
                    if (Utils.HasValue(this.hf_Account.Value))
                    {
                        if (String.Compare(inputAccount, this.hf_Account.Value) != 0)
                        {
                            if(accs.Exists(inputAccount))
                            {
                                throw new InvalidInputException("用户名已存在");
                            }
                        }
                    }
                    else if (accs.Exists(this.tb_UserName.Text.Trim()))
                    {
                        throw new InvalidInputException("用户名已存在");
                    }
                }

                if (this.tb_Pwd.Text.Length == 0)
                {
                    throw new InvalidInputException("密码不能为空");
                }


                if (Int32.TryParse(this.hf_BookId.Value, out bookId) && Int32.TryParse(this.ddl_CourseList.SelectedValue, out courseId))
                {
                    BooksDS.BookAccessRow bookAccess = accs.BookAccessSchema.NewBookAccessRow();
                    bookAccess.BookId = bookId;
                    bookAccess.CourseId = courseId;
                    bookAccess.AccessAccount = this.tb_UserName.Text.Trim();
                    bookAccess.AccessCode = this.tb_Pwd.Text;

                    ChaptersDS.ChapterAccessRow chapterAccess = accs.ChapterAccessSchema.NewChapterAccessRow();
                    foreach (RepeaterItem item in this.rp_ChapterList.Items)
                    {
                        CheckBox cb = item.FindControl("cb_Accessibility") as CheckBox;
                        bool check = cb.Checked;
                        HiddenField hf_ChapterId = item.FindControl("hf_ChpapterId") as HiddenField;

                        chapterAccess.ChapterId = Int32.Parse(hf_ChapterId.Value);
                        if (check)
                            chapterAccess.Accessibility = 1;
                        else
                            chapterAccess.Accessibility = 0;

                        chapterAccess.CourseId = courseId;

                        bool result = accs.SubmitChapterAccess(chapterAccess);

                        if (!result)
                        {
                            throw new Exception("访问权限设置失败，请重试");
                        }
                    }

                    if (accs.SubmitBookAccess(bookAccess))
                    {
                        SetInfoMessage("访问权限设置成功");
                    }
                    else
                    {
                        SetErrorMessage("用户名和密码设置失败，请重试");
                    }
                }
            }
            catch (Exception ex)
            {
                SetErrorMessage(ex.Message);
                Logger.Log(ex);
            }
        }

        protected void cb_SelectAll_CheckedChanged(object sender, EventArgs e)
        {
            foreach (RepeaterItem item in this.rp_ChapterList.Items)
            {
                CheckBox cb = item.FindControl("cb_Accessibility") as CheckBox;
                cb.Checked = this.cb_SelectAll.Checked;
            }   
        }

        protected void btn_Return_Click(object sender, EventArgs e)
        {
            Response.Redirect(String.Format("~/Auth/Teacher/ApplicationDetail.aspx?{0}={1}", QueryKeys.BOOK_ID, this.hf_BookId.Value));
        }

        protected void rp_ChapterList_ItemDataBound(object sender, RepeaterItemEventArgs e)
        {
            //绑定设定的状态，如果未设置过访问权限，则默认全选，否则使用存储的记录
            ChaptersDS.ChapterAccessRow row;
            AccessSystem accessSys = new AccessSystem();
            
            CheckBox cb = e.Item.FindControl("cb_Accessibility") as CheckBox;
            HiddenField hf = e.Item.FindControl("hf_ChpapterId") as HiddenField;

            if (cb != null && hf != null)
            {
                cb.Checked = true;
                try
                {
                    int chapterId = Int32.Parse(hf.Value);
                    row = accessSys.GetChapterByChapterId(chapterId);

                    if (row != null)
                    {
                        if (row.Accessibility == 0)
                            cb.Checked = false;
                    }
                }
                catch { }
            }
        }
    }
}
